<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试购物车功能（含测试数据）</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2e7d32;
            text-align: center;
            margin-bottom: 30px;
        }
        .test-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .test-section h3 {
            color: #2e7d32;
            margin-top: 0;
        }
        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        button {
            background-color: #2e7d32;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #1b5e20;
        }
        .success {
            color: #2e7d32;
            background-color: #e8f5e8;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .error {
            color: #d32f2f;
            background-color: #ffebee;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .info {
            color: #1976d2;
            background-color: #e3f2fd;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .warning {
            color: #f57c00;
            background-color: #fff3e0;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .step {
            margin: 10px 0;
            padding: 10px;
            border-left: 4px solid #2e7d32;
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 测试购物车功能（含测试数据）</h1>
        
        <div class="step">
            <h3>📋 测试步骤：</h3>
            <ol>
                <li>首先执行数据库脚本插入测试数据</li>
                <li>测试用户登录</li>
                <li>测试获取工厂数据</li>
                <li>测试添加商品到购物车</li>
                <li>测试获取购物车</li>
            </ol>
        </div>

        <div class="test-section">
            <h3>1. 数据库脚本</h3>
            <p>请先执行 <code>carbon-rel/test_data.sql</code> 脚本插入测试数据</p>
            <button onclick="copyScript()">复制SQL脚本</button>
            <div id="scriptStatus"></div>
        </div>

        <div class="test-section">
            <h3>2. 测试用户登录</h3>
            <button onclick="testLogin()">测试登录 (admin/123456)</button>
            <div id="loginStatus"></div>
            <pre id="loginResult"></pre>
        </div>

        <div class="test-section">
            <h3>3. 测试工厂数据</h3>
            <button onclick="testFactories()">获取工厂列表</button>
            <div id="factoryStatus"></div>
            <pre id="factoryResult"></pre>
        </div>

        <div class="test-section">
            <h3>4. 测试购物车 - 添加商品</h3>
            <button onclick="testAddToCart()">添加商品到购物车</button>
            <div id="addCartStatus"></div>
            <pre id="addCartResult"></pre>
        </div>

        <div class="test-section">
            <h3>5. 测试购物车 - 获取购物车</h3>
            <button onclick="testGetCart()">获取购物车</button>
            <div id="getCartStatus"></div>
            <pre id="getCartResult"></pre>
        </div>

        <div class="test-section">
            <h3>6. 清除测试数据</h3>
            <button onclick="clearTestData()">清除测试数据</button>
            <div id="clearStatus"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8080';
        
        function copyScript() {
            const script = `-- 完整的测试数据脚本
USE carbon_data;

-- 1. 首先临时禁用所有外键检查
SET FOREIGN_KEY_CHECKS = 0;

-- 2. 清空所有测试数据
DELETE FROM credit_log WHERE id IN (1, 2, 3);
DELETE FROM cart WHERE id IN (1, 2, 3);
DELETE FROM factories WHERE id IN (1, 2, 3);
DELETE FROM users WHERE id IN (1, 2, 3);

-- 3. 确保购物车表存在
CREATE TABLE IF NOT EXISTS \`cart\` (
    \`id\` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    \`cid\` bigint(20) NOT NULL UNIQUE COMMENT '购物车唯一标识符',
    \`user_id\` bigint(20) NOT NULL COMMENT '用户ID',
    \`factory_id\` bigint(20) NOT NULL COMMENT '工厂ID',
    \`quantity\` int(11) NOT NULL DEFAULT '1' COMMENT '商品数量',
    \`price_per_unit\` decimal(10,2) NOT NULL COMMENT '加入购物车时的单价',
    \`total_price\` decimal(10,2) NOT NULL COMMENT '总价',
    \`status\` varchar(20) NOT NULL DEFAULT 'ACTIVE' COMMENT '购物车商品状态',
    \`selected\` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否选中',
    \`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    \`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    \`is_deleted\` tinyint(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除',
    PRIMARY KEY (\`id\`),
    KEY \`idx_user_id\` (\`user_id\`),
    KEY \`idx_factory_id\` (\`factory_id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='购物车表';

-- 4. 插入测试用户数据
INSERT INTO \`users\` (\`id\`, \`uid\`, \`username\`, \`password_hash\`, \`phone_number\`, \`user_image\`, \`role\`, \`is_role_reviewed\`, \`target_credit\`, \`created_at\`, \`updated_at\`, \`is_deleted\`) VALUES
(1, 1001, 'admin', '123456', '13800138000', '', 'ADMIN', 1, 0, NOW(), NOW(), 0),
(2, 1002, 'buyer1', '123456', '13800138001', '', 'BUYER', 1, 1000, NOW(), NOW(), 0),
(3, 1003, 'seller1', '123456', '13800138002', '', 'SELLER', 1, 0, NOW(), NOW(), 0);

-- 5. 插入测试工厂数据
INSERT INTO \`factories\` (\`id\`, \`fid\`, \`owner_user_id\`, \`factory_name\`, \`factory_image\`, \`available_credit\`, \`price_per_unit\`, \`currency\`, \`created_at\`, \`updated_at\`, \`is_deleted\`) VALUES
(1, 2001001, 1003, '绿色能源工厂', '/images/factory1.jpg', 1000, 50.00, 'CNY', NOW(), NOW(), 0),
(2, 2001002, 1003, '太阳能发电厂', '/images/factory2.jpg', 800, 45.00, 'CNY', NOW(), NOW(), 0),
(3, 2001003, 1003, '风力发电站', '/images/factory3.jpg', 1200, 55.00, 'CNY', NOW(), NOW(), 0);

-- 6. 插入积分变动日志
INSERT INTO \`credit_log\` (\`id\`, \`factory_id\`, \`ref_order_id\`, \`delta_credit\`, \`type\`, \`remark\`, \`created_at\`) VALUES
(1, 2001001, NULL, 1000, 'ADD', '初始碳积分', NOW()),
(2, 2001002, NULL, 800, 'ADD', '初始碳积分', NOW()),
(3, 2001003, NULL, 1200, 'ADD', '初始碳积分', NOW());

-- 7. 重新启用外键检查
SET FOREIGN_KEY_CHECKS = 1;`;

            navigator.clipboard.writeText(script).then(() => {
                document.getElementById('scriptStatus').innerHTML = '<div class="success">✅ SQL脚本已复制到剪贴板</div>';
            }).catch(() => {
                document.getElementById('scriptStatus').innerHTML = '<div class="error">❌ 复制失败，请手动复制</div>';
            });
        }
        
        async function testLogin() {
            const statusDiv = document.getElementById('loginStatus');
            const resultDiv = document.getElementById('loginResult');
            
            statusDiv.innerHTML = '<div class="info">正在登录...</div>';
            resultDiv.textContent = '';
            
            try {
                const response = await fetch(`${API_BASE_URL}/user/login?username=admin&password=123456`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                const data = await response.json();
                
                if (response.ok && data.code === '1') {
                    localStorage.setItem('currentUser', JSON.stringify(data.obj));
                    statusDiv.innerHTML = '<div class="success">✅ 登录成功！</div>';
                    resultDiv.textContent = `用户信息:\n${JSON.stringify(data.obj, null, 2)}`;
                } else {
                    statusDiv.innerHTML = '<div class="error">❌ 登录失败</div>';
                    resultDiv.textContent = `错误信息: ${data.message || '未知错误'}\n响应数据: ${JSON.stringify(data, null, 2)}`;
                }
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">❌ 登录请求失败</div>';
                resultDiv.textContent = `错误信息: ${error.message}`;
            }
        }
        
        async function testFactories() {
            const statusDiv = document.getElementById('factoryStatus');
            const resultDiv = document.getElementById('factoryResult');
            
            statusDiv.innerHTML = '<div class="info">正在获取工厂数据...</div>';
            resultDiv.textContent = '';
            
            try {
                const response = await fetch(`${API_BASE_URL}/factory/get-factories`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                const data = await response.json();
                
                if (response.ok && data.code === '1') {
                    statusDiv.innerHTML = '<div class="success">✅ 获取工厂数据成功！</div>';
                } else {
                    statusDiv.innerHTML = '<div class="error">❌ 获取工厂数据失败</div>';
                }
                
                resultDiv.textContent = `工厂数据:\n${JSON.stringify(data, null, 2)}`;
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">❌ 获取工厂数据请求失败</div>';
                resultDiv.textContent = `错误信息: ${error.message}`;
            }
        }
        
        async function testAddToCart() {
            const statusDiv = document.getElementById('addCartStatus');
            const resultDiv = document.getElementById('addCartResult');
            
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                statusDiv.innerHTML = '<div class="error">❌ 请先登录</div>';
                resultDiv.textContent = '没有找到用户数据';
                return;
            }
            
            const userData = JSON.parse(currentUser);
            const userId = userData.id || userData.uid || 1;
            
            statusDiv.innerHTML = '<div class="info">正在测试添加商品到购物车...</div>';
            resultDiv.textContent = '';
            
            try {
                const cartData = {
                    userId: userId,
                    factoryId: 1, // 使用测试工厂ID（数据库主键）
                    quantity: 2
                };
                
                const response = await fetch(`${API_BASE_URL}/cart/add`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(cartData)
                });
                
                const data = await response.json();
                
                if (response.ok && data.code === '1') {
                    statusDiv.innerHTML = '<div class="success">✅ 添加商品到购物车成功！</div>';
                } else {
                    statusDiv.innerHTML = '<div class="error">❌ 添加商品到购物车失败</div>';
                }
                
                resultDiv.textContent = `测试详情:\n用户ID: ${userId}\n请求数据: ${JSON.stringify(cartData, null, 2)}\n响应数据: ${JSON.stringify(data, null, 2)}`;
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">❌ 添加商品到购物车请求失败</div>';
                resultDiv.textContent = `错误信息: ${error.message}`;
            }
        }
        
        async function testGetCart() {
            const statusDiv = document.getElementById('getCartStatus');
            const resultDiv = document.getElementById('getCartResult');
            
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                statusDiv.innerHTML = '<div class="error">❌ 请先登录</div>';
                resultDiv.textContent = '没有找到用户数据';
                return;
            }
            
            const userData = JSON.parse(currentUser);
            const userId = userData.id || userData.uid || 1;
            
            statusDiv.innerHTML = '<div class="info">正在测试获取购物车...</div>';
            resultDiv.textContent = '';
            
            try {
                const response = await fetch(`${API_BASE_URL}/cart/user/${userId}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                const data = await response.json();
                
                if (response.ok && data.code === '1') {
                    statusDiv.innerHTML = '<div class="success">✅ 获取购物车成功！</div>';
                } else {
                    statusDiv.innerHTML = '<div class="error">❌ 获取购物车失败</div>';
                }
                
                resultDiv.textContent = `测试详情:\n用户ID: ${userId}\n响应数据: ${JSON.stringify(data, null, 2)}`;
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">❌ 获取购物车请求失败</div>';
                resultDiv.textContent = `错误信息: ${error.message}`;
            }
        }
        
        function clearTestData() {
            localStorage.removeItem('currentUser');
            localStorage.removeItem('currentCompany');
            document.getElementById('clearStatus').innerHTML = '<div class="success">✅ 测试数据已清除</div>';
        }
        
        // 页面加载时自动测试
        window.onload = function() {
            testLogin();
        };
    </script>
</body>
</html>
